﻿$(function () {
    Show()
})
function refesh() {
    location.reload();
}

var obj = {
    allocationId: '',
    allocationNo: '',
    associateNumber: '',
    aWarehouseName: '',
    singleTime: '',
    singleMaker: '',
    allocationRemarks: '',
    examinePeople: '',
    examineReason: '',
    allocationStatus:''
}
//显示
function Show() {
    layui.use('table', function () {
        var form = layui.form;
        var table = layui.table;

        var allocationNo = $("#allocationNo").val();
        var createTime = $("#createTime").val();
        var allocationStatus = $("#allocationStatus").val();
        $.ajax({
            url: '../Warehouse/GetAllocationShow', // 后端接口地址，需替换为实际地址
            type: 'get',
            data: {
                allocationNo: allocationNo,
                createTime: createTime,
                allocationStatus: allocationStatus || 0,
                pageIndex: 1,
                pageSize: 100,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                res = JSON.parse(res)
                // res 是从后端获取到的 JSON 数据
                if (res.code === 0) {
                    console.log(res.data.list);
                    table.render({
                        elem: allocationtable, // 对应 HTML 中表格的 id
                        data: res.data.list, // 绑定获取到的数据
                        toolbar: '#toolbarDemo',
                        defaultToolbar: ['exports'],
                        page: true,
                        limit: 8,
                        limits: [8, 10, 15],
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'allocationNo', title: '调拨单号' },
                            { field: 'productName', title: '产品名称' },
                            { field: 'productNo', title: '产品编号' },
                            { field: 'productBatch', title: '批次' },
                            { field: 'productSpec', title: '规格' },
                            { field: 'quantity', title: '数量' },
                            { field: 'warehouseName', title: '原仓库' },
                            { field: 'binLocationName', title: '原库位' },
                            { field: 'aWarehouseName', title: '调拨仓库' },
                            { field: 'allocationStatusText', title: '状态' },
                            { field: 'examinePeople', title: '审核人' },
                            {
                                field: 'examineTime', title: '审核时间', templet: function (d) {
                                    return formatTime(d.examineTime); // 调用自定义的时间格式转换函数
                                }
                            },
                            {
                                field: '', title: '操作', width: 300,  templet: function (d) {
                                    return '<a class="layui-btn layui-btn-edit layui-btn-xs" lay-on="test-page-edit" onclick="updateData(' + d.allocationId + ')"><i class="layui-icon layui-icon-edit"></i>编辑</a> ' +
                                        '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteData(' + d.allocationProductId + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>' +
                                        '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="allocationmodel(' + d.allocationId + ')"><i class="layui-icon layui-icon-search"></i>查看</a>' +
                                        '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="allocationaudit(' + d.allocationId + ')"><i class="layui-icon layui-icon-util"></i>审批</a>'
                                        ;
                                }
                            }
                        ]]
                    });
                } else {
                    console.log(res.msg);
                }
            },
            error: function () {
                console.log('获取数据失败');
            }
        });

        // 点击批量删除按钮的事件处理
        $('#batchDeleteBtn').click(function () {
            var checkStatus = table.checkStatus('allocationtable');
            var selectedIds = checkStatus.data.map(function (item) { return item.allocationProductId; });
            console.log(selectedIds)
            if (selectedIds.length === 0) {
                layer.msg('请至少选择一条要删除的数据', { icon: 2 });
                return;
            }
            layer.confirm('确定要批量删除选中的 ' + selectedIds.length + ' 条数据吗？', function (index) {
                // 发送Ajax请求到后端，传递选中的id数组进行删除操作
                $.ajax({
                    url: '../Warehouse/GetAllocationDelRange', // 后端批量删除接口地址，根据实际调整
                    type: 'POST',
                    data: { ids: JSON.stringify(selectedIds), token: localStorage.getItem("token") },
                    success: function (res) {
                        var res = JSON.parse(res)
                        console.log(res)
                        if (res.code > 0) {
                            layer.msg('批量删除成功', { icon: 1 });
                            Show()
                        } else {
                            layer.msg('批量删除失败：' + res.message, { icon: 2 });
                        }
                        layer.close(index);
                    },
                    error: function () {
                        layer.msg('请求出错，请稍后再试', { icon: 2 });
                        layer.close(index);
                    }
                });
            });
        });


        // 查看详情
        window.allocationmodel = function (id) {
            // 先根据id获取要编辑的数据，发起Ajax请求
            $.ajax({
                type: "GET",
                url: "/Warehouse/GetFanAllocation",  // 替换为实际的后台根据id获取数据的接口地址
                data: { allocationId: id, token: localStorage.getItem("token") },
                success: function (res) {
                    console.log(res)
                    var res = JSON.parse(res)
                    console.log(res)
                    $(res.data).each(function () {
                        $('#allocationId').val(this.allocationId)
                        $('#allocationNos').val(this.allocationNo)
                        $('#associateNumber').val(this.associateNumber)
                        //显示下拉框
                        $("#aWarehouseName").val(this.aWarehouseName)
                        form.render('select')

                        //反填日期框
                        var da = new Date(this.singleTime);
                        // 获取年、月、日
                        var year = da.getFullYear();
                        var month = (da.getMonth() + 1).toString().padStart(2, '0');  // 月份从0开始，因此加1
                        var day = da.getDate().toString().padStart(2, '0');  // 补充两位数字
                        // 拼接成 "yyyy-MM-dd" 格式
                        var formattedDate = `${year}-${month}-${day}`;
                        $("#singleTime").val(formattedDate)


                        $('#singleMaker').val(this.singleMaker)
                        $('#allocationRemarks').val(this.allocationRemarks)

                        obj.allocationId = this.allocationId
                        obj.allocationNo = this.allocationNo
                        obj.associateNumber = this.associateNumber
                        obj.aWarehouseName = this.aWarehouseName
                        obj.singleTime = this.singleTime
                        obj.singleMaker = this.singleMaker
                        obj.allocationRemarks = this.allocationRemarks
                    })
                },
            });
            $.ajax({
                url: '../Warehouse/GetAllocaitonShowbyid', // 后端接口地址，需替换为实际地址
                type: 'get',
                data: { allocationId: id, token: localStorage.getItem("token") },
                success: function (res) {
                    console.log(res)
                    var res = JSON.parse(res)
                    // res 是从后端获取到的 JSON 数据
                    if (res.code === 0) {
                        console.log(res.data);
                        table.render({
                            elem: allocationProduct, // 对应 HTML 中表格的 id
                            data: res.data, // 绑定获取到的数据
                            cols: [[
                                { type: 'checkbox', fixed: 'left' },
                                { field: 'productName', title: '产品名称' },
                                { field: 'productNo', title: '产品编号' },
                                { field: 'productSpec', title: '规格' },
                                { field: 'productBatch', title: '批次' },
                                { field: 'productPrice', title: '单价' },
                                { field: 'quantity', title: '数量' },
                                { field: 'binLocationName', title: '原库位' },

                            ]]
                        });

                    } else {
                        console.log(res.msg);
                    }
                },
                error: function () {
                    console.log('获取数据失败');
                }
            });

            layer.open({
                type: 1,
                title: '调拨单详情',
                content: `
                      <form class="layui-form" action="">

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">调拨单号</label>
            <div class="layui-input-inline">
                <input type="text" name="allocationNos" id="allocationNos" disabled lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">调拨仓库</label>
            <div class="layui-input-inline">
             <input type="text" name="aWarehouseName" id="aWarehouseName" disabled lay-verify="required" autocomplete="off" class="layui-input">
               
            </div>
        </div>
       
    </div>

    <div class="layui-form-item" style="margin-left:140px;margin-top:30px">
        <div class="layui-inline">
            <label class="layui-form-label">制单人</label>
            <div class="layui-input-inline">
                <input type="text" name="singleMaker" id="singleMaker" disabled autocomplete="off" lay-verify="required" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单时间</label>
            <div class="layui-input-inline">
                <input type="date" name="singleTime" id="singleTime" disabled autocomplete="off" lay-verify="required" class="layui-input">
            </div>
        </div>

    </div>
     <div class="layui-inline" style="margin-left:140px;margin-top:30px">
            <label class="layui-form-label">关联订单号</label>
            <div class="layui-input-inline">
                <input type="text" name="associateNumber" id="associateNumber" disabled lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
    <div class="layui-form-item layui-form-text" style="margin-left:130px;margin-top:30px">
        <label class="layui-form-label">备注</label>
        <div class="layui-input-block">
            <input type="text" name="allocationRemarks" id="allocationRemarks" disabled lay-verify="required" autocomplete="off" class="layui-input">
        </div>
    </div>
   
   
    <table class="layui-hide" id="allocationProduct" lay-filter="test"></table>
   
</form>
                `,
                area: ['1000px', '700px'],
                success: function () {
                    
                    // 对弹层中的表单进行初始化渲染
                    form.render();
                }
            });
        };


        // 审批
        window.allocationaudit = function (id) {
            // 先根据id获取要编辑的数据，发起Ajax请求
            $.ajax({
                type: "GET",
                url: "/Warehouse/GetFanAllocation",  // 替换为实际的后台根据id获取数据的接口地址
                data: { allocationId: id, token: localStorage.getItem("token") },
                success: function (res) {
                    console.log(res)
                    var res = JSON.parse(res)
                    console.log(res)
                    $(res.data).each(function () {
                        $('#allocationId').val(this.allocationId)
                        $('#allocationNos').val(this.allocationNo)
                        $('#associateNumber').val(this.associateNumber)
                        //显示下拉框
                        $("#aWarehouseName").val(this.aWarehouseName)
                        form.render('select')

                        //反填日期框
                        var da = new Date(this.singleTime);
                        // 获取年、月、日
                        var year = da.getFullYear();
                        var month = (da.getMonth() + 1).toString().padStart(2, '0');  // 月份从0开始，因此加1
                        var day = da.getDate().toString().padStart(2, '0');  // 补充两位数字
                        // 拼接成 "yyyy-MM-dd" 格式
                        var formattedDate = `${year}-${month}-${day}`;
                        $("#singleTime").val(formattedDate)


                        $('#singleMaker').val(this.singleMaker)
                        $('#allocationRemarks').val(this.allocationRemarks)

                        obj.allocationId = this.allocationId
                        obj.allocationNo = this.allocationNo
                        obj.associateNumber = this.associateNumber
                        obj.aWarehouseName = this.aWarehouseName
                        obj.singleTime = this.singleTime
                        obj.singleMaker = this.singleMaker
                        obj.allocationRemarks = this.allocationRemarks
                    })
                },
            });
            $.ajax({
                url: '../Warehouse/GetAllocaitonShowbyid', // 后端接口地址，需替换为实际地址
                type: 'get',
                data: { allocationId: id, token: localStorage.getItem("token") },
                success: function (res) {
                    console.log(res)
                    var res = JSON.parse(res)
                    // res 是从后端获取到的 JSON 数据
                    if (res.code === 0) {
                        console.log(res.data);
                        table.render({
                            elem: allocationProduct, // 对应 HTML 中表格的 id
                            data: res.data, // 绑定获取到的数据
                            cols: [[
                                { type: 'checkbox', fixed: 'left' },
                                { field: 'productName', title: '产品名称' },
                                { field: 'productNo', title: '产品编号' },
                                { field: 'productSpec', title: '规格' },
                                { field: 'productBatch', title: '批次' },
                                { field: 'productPrice', title: '单价' },
                                { field: 'quantity', title: '数量' },
                                { field: 'binLocationName', title: '原库位' },

                            ]]
                        });

                    } else {
                        console.log(res.msg);
                    }
                },
                error: function () {
                    console.log('获取数据失败');
                }
            });

            layer.open({
                type: 1,
                title: '调拨单审核',
                content: `
                      <form class="layui-form" action="">

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">调拨单号</label>
            <div class="layui-input-inline">
                <input type="text" name="allocationNos" id="allocationNos" disabled lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">调拨仓库</label>
            <div class="layui-input-inline">
             <input type="text" name="aWarehouseName" id="aWarehouseName" disabled lay-verify="required" autocomplete="off" class="layui-input">

            </div>
        </div>

    </div>

    <div class="layui-form-item" style="margin-left:140px;margin-top:30px">
        <div class="layui-inline">
            <label class="layui-form-label">制单人</label>
            <div class="layui-input-inline">
                <input type="text" name="singleMaker" id="singleMaker" disabled autocomplete="off" lay-verify="required" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单时间</label>
            <div class="layui-input-inline">
                <input type="date" name="singleTime" id="singleTime" disabled autocomplete="off" lay-verify="required" class="layui-input">
            </div>
        </div>

    </div>
     <div class="layui-inline" style="margin-left:140px;margin-top:30px">
            <label class="layui-form-label">关联订单号</label>
            <div class="layui-input-inline">
                <input type="text" name="associateNumber" id="associateNumber" disabled lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
    <div class="layui-form-item layui-form-text" style="margin-left:130px;margin-top:30px">
        <label class="layui-form-label">备注</label>
        <div class="layui-input-block">
         <input type="text" name="allocationRemarks" id="allocationRemarks" disabled lay-verify="required" autocomplete="off" class="layui-input">
        </div>
    </div>

   <div class="layui-form-item layui-form-text" style="margin-left:130px;margin-top:30px">
        <label class="layui-form-label">审核原因</label>
        <div class="layui-input-block">
            <textarea placeholder="请输入审核原因" name="examineReason" id="examineReason" lay-verify="required" class="layui-textarea"></textarea>
        </div>
    </div>
   
    <table class="layui-hide" id="allocationProduct" lay-filter="test"></table>
   <div class="layui-form-item" style="text-align:center;margin-top:50px">
        <button class="layui-btn" lay-submit lay-filter="demo-login">审核通过</button>
        <button class="layui-btn" lay-submit lay-filter="demo-false">审核不通过</button>
        <button type="reset" class="layui-btn layui-btn-primary" onclick="location.href='/Warehouse/AllocationShow'">取消</button>
    </div>
</form>
                `,
                area: ['1000px', '800px'],
                success: function () {
                    var obj1 = {
                        allocationId: '',
                        examinePeople: '',
                        examineReason: '',
                        allocationStatus: '',
                    };
                    // 对弹层中的表单进行初始化渲染
                    form.render();
                    // 审核通过
                    form.on('submit(demo-login)', function (data) {
                        var field = data.field;
                        obj1.allocationId = obj.allocationId
                        obj1.examinePeople ="张三"
                        obj1.examineReason = field.examineReason
                        obj1.allocationStatus = 2
                        $.ajax({
                            url: '/Warehouse/GetAllocationAudit',
                            type: 'post',
                            data: { obj1, token: localStorage.getItem("token") },
                            success: function (res) {
                                var res = JSON.parse(res)
                                console.log(field)
                                console.log(res)
                                if (res.code == 1) {
                                    layer.alert("审批成功");
                                    setTimeout(function () {
                                        location.reload();
                                    }, 2000);
                                }
                                else {
                                    layer.alert("操作失败");
                                }
                            }
                        })
                        return false; // 阻止默认 form 跳转
                    });
                    // 审核不通过
                    form.on('submit(demo-false)', function (data) {
                        var field = data.field;
                        obj1.allocationId = obj.allocationId
                        obj1.examinePeople = "张三"
                        obj1.examineReason = field.examineReason
                        obj1.allocationStatus = 3
                        $.ajax({
                            url: '/Warehouse/GetAllocationAudit',
                            type: 'post',
                            data: { obj1, token: localStorage.getItem("token") },
                            success: function (res) {
                                var res = JSON.parse(res)
                                console.log(field)
                                console.log(res)
                                if (res.code == 1) {
                                    layer.alert("审批不通过");
                                    setTimeout(function () {
                                        location.reload();
                                    }, 2000);
                                }
                                else {
                                    layer.alert("操作失败");
                                }
                            }
                        })
                        return false; // 阻止默认 form 跳转
                    });
                }
            });
        };

    });
}
// 定义删除数据的函数（此处简单示意，可参考之前详细的删除功能代码完善）
window.deleteData = function (allocationProductId) {
    console.log(allocationProductId)
    layer.confirm('确定要删除该条数据吗？', function (index) {
        $.ajax({
            type: "Post",
            url: "../Warehouse/GetAllocationDel",  // 替换为实际的后台删除数据接口地址
            data: { data: JSON.stringify({ allocationProductId: allocationProductId }),token:localStorage.getItem("token") },
            success: function (res) {
                var res=JSON.parse(res)
                if (res.code === 1) {
                    layer.alert("删除成功");
                    Show();  // 重新加载数据，刷新表格显示
                } else {
                    layer.alert("删除失败");

                }
            },
            error: function () {
                layer.msg('删除失败，请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
};



// 定义时间格式转换函数
function formatTime(timeStamp) {
    if (timeStamp) {
        var date = new Date(timeStamp);
        var year = date.getFullYear();
        var month = ('0' + (date.getMonth() + 1)).slice(-2);
        var day = ('0' + date.getDate()).slice(-2);
        var hour = ('0' + date.getHours()).slice(-2);
        var minute = ('0' + date.getMinutes()).slice(-2);
        var second = ('0' + date.getSeconds()).slice(-2);
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    return "";
}

// 点击表格上方编辑按钮的事件处理
$('#batchUpdBtn').click(function () {
    var table = layui.table;
    var checkStatus = table.checkStatus('allocationtable');
    var selectedIds = checkStatus.data.map(function (item) { return item.allocationId; });
    console.log(selectedIds)
    if (selectedIds.length === 0) {
        layer.msg('请选择一条要编辑的数据', { icon: 2 });
        return;
    }
    localStorage['allocationId'] = selectedIds;
    location.href = '/Warehouse/AllocationUpd';
});


//入库编辑
window.updateData = function (allocationId) {
    localStorage['allocationId'] = allocationId;
    location.href = '/Warehouse/AllocationUpd';
}



//仓库类型下拉框
layui.use('form', function () {
    var form = layui.form;
    $.ajax({
        url: "../Warehouse/GetAduiStatusShow",
        type: "get",
        data: { token: localStorage.getItem("token") },
        success: function (data) {
            var obj = JSON.parse(data);
            console.log(obj)
            var options = '<option value="">请选择</option>'; // 添加默认选项
            $.each(obj, function (index, item) {
                options += '<option value="' + item.value + '">' + item.text + '</option>';
            });
            $("#allocationStatus").html(options);
            form.render('select'); // 重新渲染下拉框
        },
        error: function () {
            console.log("获取数据失败");
        }
    });
});